package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: gulimall
 * @description: //Feign远程调用丢失请求通问题
 * //浏览器发送，请求头自动带了cookie->order服务->feign远程调用(创建一个新的request，没有任何请求头)->cart服务
 * //解决：加入feign远程调用请求拦截器
 * @author: 江天赐
 * @create: 2022-08-16 18:05
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//                System.out.println("RequestInterceptor线程..." + Thread.currentThread().getId());
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();//老请求
                    if (request != null) {
                        //同步请求头数据，cookie
                        //给新请求同步了老请求的Cookie
                        requestTemplate.header("Cookie", request.getHeader("Cookie"));
//                    System.out.println("feign远程之前先执行RequestInterceptor的apply方法");
                    }
                }
            }
        };
    }
}
